package com.sky.service.impl;

import cn.hutool.json.JSONUtil;
import com.sky.bo.UserLoginBO;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper usermapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //请求微信登录接口获取openid
        String url = "https://api.weixin.qq.com/sns/jscode2session";

        HashMap<String, String> paras = new HashMap<>();
        paras.put("appid", "wx084d5d60b374c2a4");
        paras.put("secret", "f5207f4068251d589cc12923acd2d759");
        paras.put("js_code", userLoginDTO.getCode());
        paras.put("grant_type", "authorization_code");

        String str = HttpClientUtil.doGet(url, paras);
        log.info(str);
        UserLoginBO bo = JSONUtil.toBean(str, UserLoginBO.class);
        log.info("openid:{}", bo.getOpenid());
        //判断open_id是否存在
        User user = usermapper.selectByOpenId(bo.getOpenid());

        if(user==null){
            //不存在->注册
            user =new User();
            user.setOpenid(bo.getOpenid());
            usermapper.add(user);
        }//已经存在
        return user;

    }
}
